<?php

/**
 * contact : 刘经理 19326416371
 * company : 版权所属 四川北星惯牌科技有限公司
 **/

namespace app\common\manager;

use app\common\constant\Constant;
use app\common\model\Address;
use app\common\model\assistant\Assistant;
use app\common\model\Config;
use app\common\model\User;
use think\Db;
use think\Exception;

class AddressManager extends BaseManager
{

    /**
     * 添加地址
     * @param User $user
     * @param $address
     * @param $latitude
     * @param $longitude
     * @param $default
     * @param bool $trans
     * @return array
     */
    public static function addAddress(User $user,$address,$latitude,$longitude,$default=Address::DEFAULT_NO,bool $trans=true):array
    {
        if ($trans){
            Db::startTrans();
        }
        try {

            if(!$addressInfo = Address::create([
                'user_id' => $user->id,
                'address'=>$address,
                'lat' => $latitude,
                'lng' => $longitude,
                'default' => $default,
                'create_time' => time(),
                'update_time' => time()
            ])){
                throw new Exception('添加失败，请稍后再试');
            }

            if ($default == Address::DEFAULT_YES){
                Address::where('user_id',$user->id)->where('id','<>',$addressInfo->id)->where('default',Address::DEFAULT_YES)->update(['default' => Address::DEFAULT_NO,'update_time'=>time()]);
            }

            if ($trans)
                Db::commit();
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
        }catch (Exception $exception){
            if ($trans){
                Db::rollback();
            }
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }

        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData()];
    }


    /**
     * 编辑地址信息
     * @param $user
     * @param $id
     * @param $address
     * @param $latitude
     * @param $longitude
     * @param $default
     * @param $trans
     * @return array
     */
    public static function editAddress($user,$id,$address,$latitude,$longitude,$default=Address::DEFAULT_NO,$trans=true):array
    {
        if ($trans){
            Db::startTrans();
        }
        try {
            $addressInfo = Address::where('id',$id)->where('user_id',$user->id)->where('delete',Address::DELETE_NO)->find();
            if (isset($addressInfo)){
                $addressInfo->address = $address;
                $addressInfo->lat = $latitude;
                $addressInfo->lng = $longitude;
                $addressInfo->default = $default;
                $addressInfo->update_time = time();
                $addressInfo->save();

                if ($default == Address::DEFAULT_YES){
                    Address::where('user_id',$user->id)->where('id','<>',$id)->where('default',Address::DEFAULT_YES)->update(['default' => Address::DEFAULT_NO,'update_time'=>time()]);
                }

                if ($trans){
                    Db::commit();
                }
                self::setStatusCode(self::$successCode);
                self::setMessage(self::$successMessage);
            }else{
                throw new Exception('当前地址不存在');
            }
        }catch (Exception $exception){
            if ($trans){
                Db::rollback();
            }
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData()];
    }


    /**
     * 删除地址
     * @param $user
     * @param $id
     * @param $trans
     * @return array
     */
    public static function deleteAddress($user,$id,$trans=true):array
    {
        if ($trans) {
            Db::startTrans();
        }
        try {
            $addressModel = new Address();
            $addressInfo = $addressModel->where('id',$id)->where('user_id', $user->id)->where('delete',Address::DELETE_NO)->find();
            if (!$addressInfo) {
                throw new Exception('地址信息不存在');
            }
            $addressInfo->delete = Address::DELETE_YES;
            $addressInfo->update_time = time();
            $addressInfo->save();

            if ($trans) {
                Db::commit();
            }
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
        } catch (Exception $exception) {
            if ($trans)
                Db::rollback();
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code' => self::getStatusCode(),'message' => self::getMessage(),'data'=>self::getData()];
    }

    public static function addressList($user,$page=1,$step=Constant::PAGE_LIMIT):array
    {
        $start = ($page-1)*$step;
        $return = ['total'=>0,'totalPage'=>1,'currentPage'=>$page,'list'=>[]];
        try {
            $addressModel = new Address();
            $count = $addressModel
                ->where('user_id',$user->id)
                ->where('delete',Address::DELETE_NO)
                ->count();

            $list = $addressModel
                ->where('user_id',$user->id)
                ->where('delete',Address::DELETE_NO)
                ->limit($start,$step)
                ->select();

            $pageData = page($count,$step,$page);
            $return['list'] = $list;
            $return = array_merge($return,$pageData);
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
            self::setData($return);
        }catch (Exception $exception){
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData()];
    }

    /**
     * 获取路费
     * @param $user
     * @param $addressId
     * @param $assistantId
     * @return array
     */
    public static function calculateDistance($user,$addressId,$assistantId):array
    {
        try {
            $addressModel = new Address();
            $addressInfo = $addressModel->where('id',$addressId)->where('user_id',$user->id)->where('delete',Address::DELETE_NO)->find();
            if (!$addressInfo){
                throw new Exception('地址信息不存在');
            }

            $assistantModel = new Assistant();
            $assistantInfo = $assistantModel->where('id',$assistantId)
                ->where('status',Assistant::STATUS_ENABLE)
                ->where('review_status',Assistant::REVIEW_STATUS_PASS)
                ->where('order_switch',Assistant::ORDER_SWITCH_ON)
                ->where('in_service',Assistant::IN_SERVICE_STATUS_OFF)
                ->find();
            if (!$assistantInfo){
                throw new Exception('助教信息不存在');
            }

            $assistantTravelAmount = $exceedAmount = 0.00;
            $baseMileage = Config::where('name','basic_mileage')->value('value');
            $baseMileagePrice = Config::where('name','basic_mileage_price')->value('value');
            $exceed_price = Config::where('name','exceed_price')->value('value');
            $distance = haversine($addressInfo->lat,$addressInfo->lng,$assistantInfo->lat,$assistantInfo->lng);
            $exceed_distance = ceil(bcsub($distance,$baseMileage,2));
            if($exceed_distance){
                $exceedAmount = bcmul($exceed_distance,$exceed_price,2);
            }
            $assistantTravelAmount = bcadd($baseMileagePrice,$exceedAmount,2);
            $return = ['distance' => bcadd($distance,0,2),'distant_amount'=>$assistantTravelAmount];
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
            self::setData($return);

        }catch (Exception $exception){

            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }

        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData()];
    }


}